package util

import (
	"context"
	"encoding/json"
	"log/slog"
	"statsphere/internal/bytesconv"
	"statsphere/model"
	"statsphere/pkg/cache"
)

var ctx = context.Background()

const (
	RuleEngineCtrl   string = "rule.engine.ctrl"
	RuleEngineResult string = "rule.engine.result"
)

func CloseRedis() {
	_ = cache.Rdb0.Close()
}

func SubscribeRedis() {
	go subscribeRedis()
	go processCtrlData()
}

func subscribeRedis() {
	pubSub := cache.Rdb0.Subscribe(ctx, RuleEngineCtrl, RuleEngineResult)
	//defer func() {
	//	_ = pubSub.Close()
	//}()

	_ch := pubSub.Channel()
	var err error
	for raw := range _ch {
		if raw.Channel == RuleEngineCtrl {
			//
			ctrlReq := new(model.ReverseCtrlStruct)
			err = json.Unmarshal(bytesconv.StringToBytes(raw.Payload), ctrlReq)
			slog.Info("反控请求", "payload", raw.Payload)
			if err != nil {
				continue
			}
			MqReq <- ctrlReq
		} else if raw.Channel == RuleEngineResult {
			//
			ctrlResp := new(model.CtrlResultStruct)
			err = json.Unmarshal(bytesconv.StringToBytes(raw.Payload), ctrlResp)
			slog.Info("反控响应", "payload", raw.Payload)
			if err != nil {
				continue
			}
			MqResp <- ctrlResp
		}
	}
}
